package com.yyfax.pay.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author AlanQiu on 2017/4/13.
 */
public class LianlianSignUtil {

	/**
	 * 根据参数字母升序排列，获取需要加密或者签名的字符串（空字符串不处理）
	 *
	 * @param param
	 * @return
	 */
	public static String getSignStr(Map<String, String> param) {
		String jsonString = JSON.toJSONString(param);
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		return getSignStr(jsonObject);
	}

	/**
	 * 根据参数字母升序排列，获取需要加密或者签名的字符串（空字符串不处理）
	 *
	 * @param param
	 * @return
	 */
	public static String getSignStr(JSONObject param) {
		StringBuffer sb = new StringBuffer();
		List<String> keys = new ArrayList<String>(param.keySet());
		Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			if ("sign".equals(key)) {
				continue;
			}
			String value = param.getString(key);
			// 空串不参与签名
			if (StringUtils.isBlank(value) || value.equalsIgnoreCase("null")) {
				continue;
			}
			sb.append(i == 0 ? "" : "&").append(key).append("=").append(value.trim());

		}
		String signSrc = sb.toString();
		if (signSrc.startsWith("&")) {
			signSrc = signSrc.replaceFirst("&", "");
		}
		return signSrc;
	}

	public static Map<String, String> objectToMap(Object obj) throws Exception {
		if (obj == null)
			return null;

		Map<String, String> map = new HashMap<>();

		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertyDescriptors) {
			String key = property.getName();
			if (key.compareToIgnoreCase("class") == 0) {
				continue;
			}
			Method getter = property.getReadMethod();
			Object value = getter != null ? getter.invoke(obj) : null;
			if (value != null) {

				map.put(key, value.toString());
			}
		}

		return map;
	}

	public static String signRSA(String privateKeyStr, String signStr) throws Exception {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(getBytesBASE64(privateKeyStr));
			KeyFactory keyf = KeyFactory.getInstance("RSA");
			PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
			// 用私钥对信息生成数字签名
			java.security.Signature signet = java.security.Signature.getInstance("MD5withRSA");
			signet.initSign(myprikey);
			signet.update(signStr.getBytes("UTF-8"));
			byte[] signed = signet.sign(); // 对信息的数字签名
			return new String(org.apache.commons.codec.binary.Base64.encodeBase64(signed));
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	// BASE64 编码的字符串 s 进行解码
	private static byte[] getBytesBASE64(String s) {
		if (s == null)
			return null;
		try {
			byte[] b = Base64.decodeBase64(s);
			return b;
		} catch (Exception e) {
			return null;
		}
	}

}
